package action;

import com.intellij.ide.IdeView;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.DataKey;
import com.intellij.openapi.actionSystem.LangDataKeys;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.project.Project;
import com.intellij.psi.*;
import org.jetbrains.annotations.NotNull;
import utils.CommonUtil;

import java.util.HashMap;
import java.util.Map;

/**
 * 生成JavaBean
 *
 * @author zfc on 2021-11-16
 */
public class GenerateJavaBeanByString extends AnAction {

    private String member = "public";
    private String pasteStr = "name String \n" +
            "age int\n"+
            "id Integer\n"
            ;

    @Override
    public void actionPerformed(@NotNull AnActionEvent event) {
        generateFile(event, "User", pasteStr);
    }

    private void generateFile(AnActionEvent event, String fileName, String pasteStr) {
        // 获得工程对象
        Project project = event.getProject();
        // 获得目录服务
        JavaDirectoryService directoryService = JavaDirectoryService.getInstance();

        // 获得当前的路径
        IdeView ideView = event.getRequiredData(LangDataKeys.IDE_VIEW);
        PsiDirectory targetDirectory = ideView.getOrChooseDirectory();

        //填入模版文件的参数
        HashMap<String,String> map= new HashMap<>();
        map.put("NAME",fileName);
        map.put("INTERFACES","implements Serializable");
        map.put("PACKAGE_NAME", CommonUtil.getPackageName(project));

        PsiClass psiClass= directoryService.createClass(targetDirectory,fileName,"GenerateFileByString",false,map);

        //开始加入字段
        WriteCommandAction.runWriteCommandAction(project,
                new Runnable() {
                    @Override
                    public void run() {
                        generateModelField(pasteStr,project,psiClass);
                    }
                });
    }

    private void generateModelField(String pasteStr,Project project,PsiClass psiClass){
        if(psiClass==null){
            return;
        }
        PsiElementFactory factory = JavaPsiFacade.getInstance(project).getElementFactory();
        //根据用户输入的字符串生产出代码
        //"name String\n"+"age int\n"+"id Integer\n";
        String[] lineString=pasteStr.split("\n");
        StringBuilder sb=new StringBuilder();
        for (String line : lineString) {
            String[] temp=line.split(" ");
            String fieldName=temp[0];
            String fieldType=temp[1];
            //public String name;
            sb.append(member+" "+fieldType+" "+fieldName+";");
            PsiField field=factory.createFieldFromText(sb.toString(),psiClass);
            psiClass.add(field);
            sb.delete(0,sb.length());
        }


    }
}
